//!important: remember to  clear cache  and restart browser after updated this file.

importScripts('socket.io.min.js');

//we can post parameter to this :
//var w = new Worker("./Scripts/sample.js?answer=42&question=ultimate");
/*
https://stackoverflow.com/questions/12381882/can-i-pass-parameters-to-js-function-when-i-create-the-new-web-workers-object/12382015
var parameters = {}
location.search.slice(1).split("&").forEach( function(key_value) { var kv = key_value.split("="); parameters[kv[0]] = kv[1]; })

var question = parameters['question'];
var answer = parameters['answer'];

*/

//
// let socket = io('http://127.0.0.1', {
//   path: '/mysocket',
//   transports: ['websocket', 'polling']
// });

//caller:this.worker = new SharedWorker('DMessageSharedWorker.js?httpServerAddr=' + httpServerAddr + '&httpProxyPath='+httpProxyPath);

let parameters = {}
location.search.slice(1).split("&").forEach(function (key_value) { var kv = key_value.split("="); parameters[kv[0]] = kv[1]; })

let httpServerAddr = parameters['httpServerAddr'];
let httpProxyPath = parameters['httpProxyPath'];

console.log(httpServerAddr, httpProxyPath);


let socket = io(httpServerAddr, {
  path: httpProxyPath,
  transports: ['websocket', 'polling']
});


socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));


let data = [];
let conns = new Set();
//every browser will trigger connect event
self.onconnect = function (e) {
  debugger
  let port = e.ports[0];
  port.rooms = new Set(); //记录这个网页需要消息的所有课程（roomName）//可以换成currNo1,qgroup1,这样的方式，这样将不仅仅限于课程！
  conns.add(port);
  port.onmessage = function (ev) {
    // send out to nodejs server at once when received message from browser

    if (ev.data.eventName == 'reportAction') {
      socket.emit(ev.data.eventName, ev.data.message);
    } else if (ev.data.eventName == 'joinRoom') {
      port.rooms.add(ev.data.message.roomName);
      socket.emit(ev.data.eventName, ev.data.message);
    } else if (ev.data.eventName == 'leaveRoom') {
      port.rooms.delete(ev.data.message.roomName);
      if (allClientsDoNotNeed(ev.data.message.roomName)) {
        socket.emit(ev.data.eventName, ev.data.message);
      }
    } else if (ev.data.eventName == 'portClosing') {

      handleRoomsBeforeDel(port);
      conns.delete(port);
      port.close();
    } else {
      socket.emit(ev.data.eventName, ev.data.message);
    }

  }
}
function handleRoomsBeforeDel(port) {
  for (let roomName of port.rooms.values()) {
    port.rooms.delete(roomName);
    if (allClientsDoNotNeed(roomName)) {
      socket.emit('leaveRoom', { roomName });
    }
  }
}

function allClientsDoNotNeed(roomName) {
  for (let p of conns.values()) {
    if (p.rooms.has(roomName)) return false;
  }
  return true;
}

//received messgae from nodejs server
socket.on('allMessage', function (data) {
  const msgArray = []
  for (let i = 0; i < data.length; i++) {
    msgArray.push(data[i].message)
  }
  const newdata = { message: msgArray, roomName: data[0].roomName, type: data[0].type }
  postAllMessage(newdata);
});

function postAllMessage(data) {
  for (let p of conns.values()) {
    if (p.rooms.has(data.roomName)) { //存在这个roomName，那就发送出去！！
      p.postMessage(data);
    }
  }
}

